gcapp.set "messageVisible","false"
gcapp.get doc,frontDocument
doc.get recRef,"parentStructure"
recRef.findStructures sours,"SOUR"
if @sours.count=0
  Beep
  exit
endif

! move sources at next level to a new list
! Each item in this list is a list about one source
CreateList toSort
#sortLevel=@recRef.level+1
Repeat "#i",0,@sours.count-1
  sours.#i.get sour
  if @sour.level!=#sortLevel
    ! skip wrong level
    continue
  endif
  doc.get sourRec,"recordWithID"&@sour.contents
  
  ! list for this source {structure, sdn, title}
  Createlist oneSour,sour
  
  ! look for a date in source details, then in
  ! source record, last in level 3 of source record
  sour.evaluateExpression "#sdate","DATA.DATE"
  if #sdate=""
    ifDef sourRec
      #sdate=@sourRec.sourceDate
      if #sdate=""
        sourRec.findStructures dates,"DATE"
        Repeat "#j",0,@dates.count-1
          dates.#j.get oneDate
          if @oneDate.level!=3
            ! skips DATE in a CHAN structure
            continue
          endif
          #sdate=@oneDate.contents
          if #sdate<>""
            break
          endif
        EndRepeat
      endif
    endif
  endif
  
  ! Add SDN to list (or large number if no valid date found)
  if #sdate<>""
    SDNRange "#drange",#sdate
    #sdate=0.5*(#drange[1]+#drange[2])
    if #sdate=0
      #sdate=9999999
    endif
  else
    #sdate= 9999999
  endif
  oneSour.addString #sdate
  
  ! Add source name
  #sname="ZZZZZZZZ"
  ifDef sourRec
    #sname=@sourRec.sourceTitle
    if #sname=""
      #sname="ZZZZZZZZ"
    endif
  endif
  oneSour.addString #sname
  
  ! Add this source's list to master sorting list
  toSort.addObject oneSour
EndRepeat

! Exit if one or fewer found to be sorted
if @toSort.count<=1
  Beep
  exit
endif

! Bubble sort (OK because very few items be here)
#moves=0
Repeat
  #sorted="yes"
  Repeat "#i",0,@toSort.count-2
    toSort.#i.get d1
    #j=#i+1
    toSort.#j.get d2
    
    ! if d2 before d1, swap
    #swap="no"
    if @d2.1<@d1.1
      #swap="yes"
    else if @d2.1=@d1.1
      ! if dates the same, check name instead
      if @d2.2<@d1.2
        #swap="yes"
      endif
    endif
    if #swap="yes"
      toSort.insertObject d2,#i
      toSort.remove #i+2
      #sorted="no"
      #moves+=1
    endif
  EndRepeat
  
  ! exit when pass had no swaps
  if #sorted="yes"
    break
  endif
EndRepeat

! Exit if original order was already correct
if #moves=0
  Beep
  exit
endif

! Debug resulting sort order
!Repeat "#i",0,@toSort.count-1
!  toSort.#i.get d1
!  d1.0.get adate
!  write @adate.contents&","&@d1.1&","&@d1.2&return
!EndRepeat

! Step back through sources moving to new oder
doc.beginUndo
Repeat "#i",@toSort.count-2,0,-1
  toSort.#i.get dmove
  #j=#i+1
  toSort.#j.get dbefore
  dmove.0.move dbefore.0
EndRepeat
doc.endUndo "Sort Sources"
